<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-16 20:54:02
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-18 13:06:41
 * @FilePath: /free-learning/src/views/system/carousel/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CarouselView from "./view.vue";
import {
  getCarouselList,
  addCarousel,
  editCarousel,
  deleteCarousel,
  activeCarousel,
} from "@/api/system/carousel";
import type { Carousel } from "@/api/system/carousel/type";
import ImageUpload from "@/components/Upload/ImageUpload.vue";
import moment from "moment";

defineOptions({
  name: "Carousel",
});

// 表格数据
const tableData = ref<Carousel[]>([]);
const loading = ref(false);

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref("添加轮播图");
const isEdit = ref(false);

// 表单数据
const formData = reactive<Carousel>({
  id: 0,
  title: "",
  description: "",
  buttonText: "",
  link: "",
  backgroundImage: "",
  sortOrder: 0,
  isActive: 0,
  isShowButton: 0,
  isShowTitle: 0,
  isShowDescription: 0,
  createTime: "",
  updateTime: "",
  backgroundColor: "",
  desColor: "",
  titleColor: "",
  isClickBackgroundLink: 0,
});

// 监听显示设置变化
watch(
  () => formData.isShowTitle,
  (val) => {
    if (!val) formData.title = "";
  }
);

watch(
  () => formData.isShowDescription,
  (val) => {
    if (!val) formData.description = "";
  }
);

watch(
  () => formData.isShowButton,
  (val) => {
    if (!val) {
      formData.buttonText = "";
      formData.link = "";
    }
  }
);

// 判断是否是外部链接
const isExternalLink = (link: string) => {
  return link.startsWith("http://") || link.startsWith("https://");
};

// 获取轮播图列表
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getCarouselList();
    tableData.value = res || [];
  } catch (error) {
    ElMessage.error("获取轮播图列表失败");
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formData.id = 0;
  formData.title = "";
  formData.description = "";
  formData.buttonText = "";
  formData.link = "";
  formData.backgroundImage = "";
  formData.sortOrder = 0;
  formData.isActive = 0;
  formData.isShowButton = 0;
  formData.isShowTitle = 0;
  formData.isShowDescription = 0;
};

// 打开对话框
const handleDialog = (type: "add" | "edit", row?: Carousel) => {
  dialogVisible.value = true;
  isEdit.value = type === "edit";
  dialogTitle.value = type === "add" ? "添加轮播图" : "编辑轮播图";

  if (type === "edit" && row) {
    Object.assign(formData, row);
  } else {
    resetForm();
  }
  formData.backgroundColor = formData.backgroundColor || "#3579f6";
  formData.desColor = formData.desColor || "#ffffff";
  formData.titleColor = formData.titleColor || "#ffffff";
};

// 保存轮播图
const handleSave = async () => {
  try {
    if (isEdit.value) {
      formData.updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
      formData.createTime = moment().format("YYYY-MM-DD HH:mm:ss");
      await editCarousel(formData);
      ElMessage.success("编辑成功");
    } else {
      formData.updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
      await addCarousel(formData);
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error(isEdit.value ? "编辑失败" : "添加失败");
  }
};

// 删除轮播图
const handleDelete = async (row: Carousel) => {
  try {
    await ElMessageBox.confirm("确定要删除该轮播图吗？", "提示", {
      type: "warning",
    });
    await deleteCarousel(row);
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 启用/禁用轮播图
const handleActive = async (row: Carousel) => {
  try {
    await activeCarousel(row);
    ElMessage.success(row.isActive === 0 ? "启用成功" : "禁用成功");
    fetchData();
  } catch (error) {
    ElMessage.error(row.isActive === 0 ? "启用失败" : "禁用失败");
  }
};

// 图片上传成功回调
const handleUploadSuccess = (url: string) => {
  formData.backgroundImage = url;
};
const previewVisible = ref(false);
const viewCarousel = ref<Carousel>();
const handlePreview = (row?: Carousel) => {
  previewVisible.value = true;
  viewCarousel.value = row;
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="carousel-manage">
    <div class="header">
      <h2>轮播图管理</h2>
      <div>
        <el-button @click="handlePreview()">预览</el-button>
        <el-button type="primary" @click="handleDialog('add')">添加轮播图</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" align="center" />
      <el-table-column prop="title" label="标题" min-width="120" show-overflow-tooltip />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column label="背景图片" width="180">
        <template #default="{ row }">
          <el-image
            :src="row.backgroundImage"
            :preview-src-list="[row.backgroundImage]"
            fit="cover"
            style="width: 150px; height: 80px"
          >
            <template #error>
              <div class="image-slot">未上传图片</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isActive === 1 ? 'success' : 'info'">
            {{ row.isActive === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="显示设置" width="200">
        <template #default="{ row }">
          <el-tag v-if="row.isShowTitle === 1" class="mr-2">标题</el-tag>
          <el-tag v-if="row.isShowDescription === 1" class="mr-2">描述</el-tag>
          <el-tag v-if="row.isShowButton === 1">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handlePreview(row)">预览</el-button>
          <el-button type="primary" link @click="handleDialog('edit', row)">编辑</el-button>
          <el-button
            :type="row.isActive === 0 ? 'success' : 'warning'"
            link
            @click="handleActive(row)"
          >
            {{ row.isActive === 0 ? "启用" : "禁用" }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <div class="h-100 overflow-y-scroll">
        <el-form :model="formData" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-checkbox v-model="formData.isShowTitle" :true-label="1" :false-label="0">
              显示标题
            </el-checkbox>
            <el-input
              v-model="formData.title"
              placeholder="请输入标题"
              :disabled="!formData.isShowTitle"
            >
              <template #append>
                <el-color-picker v-model="formData.titleColor" :disabled="!formData.isShowTitle" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-checkbox v-model="formData.isShowDescription" :true-label="1" :false-label="0">
              显示描述
            </el-checkbox>
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述"
              :disabled="!formData.isShowDescription"
            />
            <el-color-picker v-model="formData.desColor" :disabled="!formData.isShowTitle" />
          </el-form-item>
          <el-form-item label="按钮文本" prop="buttonText">
            <el-checkbox v-model="formData.isShowButton" :true-label="1" :false-label="0">
              显示按钮
            </el-checkbox>
            <el-form-item>
              <el-checkbox
                v-model="formData.isClickBackgroundLink"
                style="margin-left: 10px"
                :true-label="1"
                :false-label="0"
              >
                是否点击背景跳转
              </el-checkbox>
            </el-form-item>
            <el-input
              v-model="formData.buttonText"
              placeholder="请输入按钮文本"
              :disabled="!formData.isShowButton"
            />
          </el-form-item>
          <el-form-item prop="link">
            <template #label>
              <div class="flex items-center">
                <div>链接</div>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="以 http或https的链接打开模式为新标签页打开"
                  placement="top-start"
                >
                  <el-icon><Warning /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model="formData.link"
              placeholder="请输入链接"
              :disabled="!formData.isShowButton && !formData.isClickBackgroundLink"
            />
          </el-form-item>

          <el-form-item label="背景图片" prop="backgroundImage">
            <ImageUpload
              v-model="formData.backgroundImage"
              :limit="1"
              accept="image/*"
              @success="handleUploadSuccess"
            />
          </el-form-item>
          <el-form-item>
            <template #label>
              <div class="flex items-center">
                <div>背景颜色</div>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="当不上传背景图片时，应用此处背景颜色"
                  placement="top-start"
                >
                  <el-icon><Warning /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-color-picker v-model="formData.backgroundColor" />
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="formData.sortOrder" :min="0" :max="999" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="previewVisible" title="预览轮播图" width="800" destroy-on-close>
      <div>
        <CarouselView :viewCarousel="viewCarousel" />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.carousel-manage {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .mr-2 {
    margin-right: 8px;
  }
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 18px;
  }
}
</style>
